package com.sxt.server.handler;

import com.lmax.disruptor.RingBuffer;
import com.sxt.server.common.model.TranslatorData;
import com.sxt.server.common.model.TranslatorDataWapper;

import io.netty.channel.ChannelHandlerContext;

/**
 * 消息生产者
 * 
 * @author Administrator
 *
 */
public class MessageProducer {

	private String producerId;
	// 核心类，环形数组
	public RingBuffer<TranslatorDataWapper> ringBuffer;

	public MessageProducer(String producerId, RingBuffer<TranslatorDataWapper> ringBuffer) {
		this.producerId = producerId;
		this.ringBuffer = ringBuffer;
	}

	/**
	 * 通过构造方法初始化环形数组核心类
	 * 
	 * @param ringBuffer
	 */
	public MessageProducer(RingBuffer<TranslatorDataWapper> ringBuffer) {
		this.ringBuffer = ringBuffer;
	}

	/**
	 * 生产事件（数据）的方法，实质是往环形数组里放置数据
	 * 
	 * @param data
	 */
	public void onData(TranslatorData data, ChannelHandlerContext ctx) {
		// 1.ringBuffer获取下一个序号，也就是要放置数据的位置
		long sequence = this.ringBuffer.next();
		try {
			// 2.取出空的事件队列
			TranslatorDataWapper wapper = this.ringBuffer.get(sequence);
			// 3.获取事件队列传递的数据
			wapper.setData(data);
			wapper.setCtx(ctx);
		} finally {
			// 4.发布事件
			this.ringBuffer.publish(sequence);
		}
	}
}
